<script setup>
import { watch } from "vue";
import "@material/web/elevation/elevation.js";
import "@material/web/icon/icon.js";
import "@material/web/iconbutton/icon-button.js";

const emit = defineEmits(["close"]);
const props = defineProps(["action", "close", "show"]);

let timer = undefined;

watch(() => props.show, show => {
  if (timer !== undefined) {
    clearTimeout(timer);
  }
  if (show) {
    timer = setTimeout(() => {
      emit("close");
    }, 5000);
  }
});
</script>

<template>
  <Transition name="snackbar">
    <div v-if="show" class="snackbar body-medium">
      <p class="content">
        <slot></slot>
      </p>
      <div class="right">
        <p class="action" v-if="action !== undefined">
          <slot name="action"></slot>
        </p>
        <p class="close" v-if="close !== undefined">
          <md-icon-button @click="$emit('close')">
            <md-icon>close</md-icon>
          </md-icon-button>
        </p>
      </div>
      <md-elevation></md-elevation>
    </div>
  </Transition>
</template>

<style scoped>
.snackbar {
  --snackbar-side-padding: 32px;
  --snackbar-height: 48px;
  position: fixed;
  width: 320px;
  bottom: var(--snackbar-side-padding);
  left: 0;
  right: 0;
  margin: 0 auto;
  border-radius: 4px;
  background-color: var(--md-sys-color-inverse-surface);
  color: var(--md-sys-color-inverse-on-surface);
  display: flex;
  height: var(--snackbar-height);
  align-items: center;
  --md-elevation-level: 3;
  --md-elevation-shadow-color: var(--md-sys-color-shadow);
}

.snackbar>.content {
  padding: 0 16px;
}

.snackbar>.right {
  margin-left: auto;
  margin-right: 0;
  display: flex;
  height: 100%;
  align-items: center;
}

.snackbar>.right>.action {
  padding: 0 8px;
  --md-text-button-container-shape: 4px;
  --md-sys-color-primary: var(--md-sys-color-inverse-primary);
}

.snackbar>.right>.close {
  padding-right: 4px;
  /* Hack of --md-icon-button-icon-color don't affect when hovering */
  --md-sys-color-on-surface-variant: var(--md-sys-color-inverse-on-surface);
  display: flex;
  align-items: center;
}

.snackbar-enter-active,
.snackbar-leave-active {
  transition-property: opacity, transform;
  transition-duration: var(--md-sys-motion-duration-medium2);
  transition-timing-function: var(--md-sys-motion-easing-standard);
}

.snackbar-enter-to,
.snackbar-leave-from {
  opacity: 1;
  transform: translateY(0);
}

.snackbar-enter-from,
.snackbar-leave-to {
  opacity: 0;
  transform: translateY(calc(var(--snackbar-side-padding) + var(--snackbar-height)));
}
</style>
